<?php
/**
* @version   $Id: admin.scribblemaps.php 4 2010-10-05 09:23:50Z edo888 $
* @package   Scribble Maps
* @copyright Copyright (C) 2010 Edvard Ananyan. All rights reserved.
* @license   GNU/GPL, see LICENSE.php
*/

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

class ScribbleMapsController extends JController {
    function __construct($default = array()) {
        parent::__construct($default);
        $this->registerTask('add' , 'editMap');
        $this->registerTask('edit', 'editMap');
        $this->registerTask('save', 'saveMap');
        $this->registerTask('apply', 'saveMap');
        $this->registerTask('remove', 'removeMap');
    }

    function showMaps() {
        global $mainframe, $option;

        $db               =& JFactory::getDBO();
        $filter_order     = $mainframe->getUserStateFromRequest("$option.filter_order",'filter_order','m.id');
        $filter_order_Dir = $mainframe->getUserStateFromRequest("$option.filter_order_Dir",'filter_order_Dir','');
        $search           = $mainframe->getUserStateFromRequest("$option.search",'search','');
        $search           = $db->getEscaped(trim(JString::strtolower($search)));

        $limit      = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        $limitstart = $mainframe->getUserStateFromRequest($option.'limitstart', 'limitstart', 0, 'int');

        $where = array();

        if($search)
            $where[] = '(title LIKE "%'.$search.'%" OR description LIKE "%'.$search.'%")';

        $where   = (count($where) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
        $orderby = ' ORDER BY '. $filter_order .' '. $filter_order_Dir;

        $query = 'SELECT COUNT(m.id) FROM #__scribblemaps as m ' . $where;
        $db->setQuery($query);
        $total = $db->loadResult();

        jimport('joomla.html.pagination');
        $pageNav = new JPagination($total,$limitstart,$limit);

        $query = 'SELECT m.* FROM #__scribblemaps as m ' . $where . ' ' . $orderby;
        $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
        $rows = $db->loadObjectList();

        if($db->getErrorNum()) {
            echo $db->stderr();
            return false;
        }

        // table ordering
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order']     = $filter_order;

        // search filter
        $lists['search'] = $search;

        ScribbleMapsView::showMaps($rows, $pageNav, $option, $lists);
    }

    function editMap() {
        $db =& JFactory::getDBO();

        if($this->_task == 'edit') {
            $cid = JRequest::getVar('cid', array(0), 'method', 'array');
            $cid = array((int) $cid[0]);
        } else {
            $cid = array( 0 );
        }

        $query = 'select m.* from #__scribblemaps as m where m.id = ' . $cid[0];
        $db->setQuery($query);
        $row = $db->loadObject();

        ScribbleMapsView::editMap($row);
    }

    function saveMap() {
        $db =& JFactory::getDBO();
        $id = JRequest::getInt('id', 0);

        if($id == 0) { // going to insert new map
            // constructing the Map object
            $map = new JTable('#__scribblemaps', 'id', $db);
            $map->set('map_id', JRequest::getVar('map_id'));
            $map->set('title', JRequest::getVar('title'));
            $map->set('width', JRequest::getInt('width'));
            $map->set('height', JRequest::getInt('height'));
            $map->set('description', JRequest::getVar('description'));
            $map->store();

            $this->setRedirect('index.php?option=com_scribblemaps', JText::_('Map successfully created'));
        } else { // going to update map

            // constructing the map object
            $map = new JTable('#__scribblemaps', 'id', $db);
            $map->set('id', $id);
            $map->set('map_id', null);
            $map->set('title', null);
            $map->set('width', null);
            $map->set('height', null);
            $map->set('description', null);
            $map->load();

            //$map->set('map_id', JRequest::getVar('map_id'));
            $map->set('title', JRequest::getVar('title'));
            $map->set('width', JRequest::getInt('width'));
            $map->set('height', JRequest::getInt('height'));
            $map->set('description', JRequest::getVar('description'));
            $map->store();


            if($this->_task == 'save')
                $this->setRedirect('index.php?option=com_scribblemaps', JText::_('Map successfully saved'));
            elseif($this->_task == 'apply')
                $this->setRedirect('index.php?option=com_scribblemaps&task=edit&cid[]='.$id, JText::_('Map successfully saved'));
            else
                $this->setRedirect('index.php?option=com_scribblemaps', JText::_('Unknown task'));
        }
    }

    function removeMap() {
        $db   =& JFactory::getDBO();
        $cid  = JRequest::getVar( 'cid', array(), '', 'array' );

        for($i = 0, $n = count($cid); $i < $n; $i++) {
            $query = "delete from #__scribblemaps where id = $cid[$i]";
            $db->setQuery($query);
            $db->query();
        }

        $this->setRedirect('index.php?option=com_scribblemaps', JText::_('Map(s) successfully deleted'));
    }
}


class ScribbleMapsView {
    function showMaps($rows, $pageNav, $options, $lists) {
        //JSubMenuHelper::addEntry(JText::_('Maps'), 'index.php?option=com_scribblemaps', true);

        JHTML::_('behavior.tooltip');
        jimport('joomla.filter.output');
        ?>
        <form action="index.php?option=com_scribblemaps" method="post" name="adminForm">

        <table>
            <tr>
                <td align="left" width="100%">
                    <?php echo JText::_('Filter'); ?>:
                    <input type="text" name="search" id="search" value="<?php echo $lists['search'];?>" class="text_area" onchange="document.adminForm.submit();" />
                    <button onclick="this.form.submit();"><?php echo JText::_('Go'); ?></button>
                    <button onclick="document.getElementById('search').value='';this.form.submit();"><?php echo JText::_('Reset'); ?></button>
                </td>
                <td nowrap="nowrap">
                </td>
            </tr>
        </table>

        <div id="tablecell">
            <table class="adminlist">
            <thead>
                <tr>
                    <th width="1%">
                        <?php echo JText::_('NUM'); ?>
                    </th>
                    <th width="1%" align="center">
                        <input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count( $rows ); ?>);" />
                    </th>
                    <th width="6%" class="title">
                        <?php echo JHTML::_('grid.sort', 'Map ID', 'm.map_id', @$lists['order_Dir'], @$lists['order']); ?>
                    </th>
                    <th width="6%" class="title">
                        <?php echo JHTML::_('grid.sort', 'Title', 'm.title', @$lists['order_Dir'], @$lists['order']); ?>
                    </th>
                    <th width="6%" class="title">
                        <?php echo JHTML::_('grid.sort', 'Width', 'm.width', @$lists['order_Dir'], @$lists['order']); ?>
                    </th>
                    <th width="6%" class="title">
                        <?php echo JHTML::_('grid.sort', 'Height', 'm.height', @$lists['order_Dir'], @$lists['order']); ?>
                    </th>
                    <th width="1%" nowrap="nowrap">
                        <?php echo JHTML::_('grid.sort', 'ID', 'm.id', @$lists['order_Dir'], @$lists['order']); ?>
                    </th>
                </tr>
            </thead>
            <?php
            $k = 0;
            for($i=0, $n=count($rows); $i < $n; $i++) {
                $row = &$rows[$i];
                JFilterOutput::objectHTMLSafe($row, ENT_QUOTES);

                $link        = JRoute::_('index.php?option=com_scribblemaps&task=edit&cid[]='. $row->id);
                @$checked     = JHTML::_('grid.checkedout', $row, $i);
                ?>
                <tr class="<?php echo "row$k"; ?>">
                    <td>
                        <?php echo $pageNav->getRowOffset( $i ); ?>
                    </td>
                    <td align="center">
                        <?php echo $checked; ?>
                    </td>
                    <td align="center">
                        <a href="<?php echo $link; ?>" title="<?php echo JText::_( 'Edit Map' ); ?>">
                            <?php echo $row->map_id; ?></a>
                    </td>
                    <td align="center">
                        <?php echo $row->title; ?>
                    </td>
                    <td align="center">
                        <?php echo $row->width; ?>
                    </td>
                    <td align="center">
                        <?php echo $row->height; ?>
                    </td>
                    <td align="center">
                        <?php echo $row->id; ?>
                    </td>
                </tr>
                <?php
                $k = 1 - $k;
            }
            ?>
            <tfoot>
                <td colspan="13">
                    <?php echo $pageNav->getListFooter(); ?>
                </td>
            </tfoot>
            </table>
        </div>

        <input type="hidden" name="option" value="com_scribblemaps" />
        <input type="hidden" name="task" value="" />
        <input type="hidden" name="boxchecked" value="0" />
        <input type="hidden" name="filter_order" value="<?php echo $lists['order']; ?>" />
        <input type="hidden" name="filter_order_Dir" value="" />
        <?php echo JHTML::_( 'form.token' ); ?>
        </form>
        <?php
    }

    function editMap($row) {
        //TODO: Make sure the user is authorized to view this page
        jimport('joomla.filter.output');
        JFilterOutput::objectHTMLSafe($row, ENT_QUOTES);

        //$document =& JFactory::getDocument();
        //$document->addScript(JURI::root(true).'/modules/mod_gtranslate/jquery-translate.js');
        JHTML::_('behavior.modal');

        //echo '<pre>', print_r($row, true), '</pre>';
    ?>
        <script language="javascript" type="text/javascript">
        function submitbutton(pressbutton) {
            var form = document.adminForm;
            if(pressbutton == 'cancel') {
                submitform(pressbutton);
                return;
            }

            // validation
            if(form.map_id && form.map_id.value == "")
                alert('Map ID is required');
            else if(form.title.value == "")
                alert('Map title is required');
            else if(form.width.value == "")
                alert('Map width is required');
            else if(form.height.value == "")
                alert('Map height is required');
            else
                submitform(pressbutton);
        }
        </script>
        <form action="index.php" method="post" name="adminForm">

        <fieldset class="adminform">
            <legend><?php echo JText::_('Details'); ?></legend>

            <table class="admintable">
            <tr>
                <td width="200" class="key">
                    <label for="map_id">
                        <?php echo JText::_( 'Map ID' ); ?>
                    </label>
                </td>
                <td>
                    <?php
                    if(!empty($row->map_id))
                        echo $row->map_id;
                    else
                        echo '<input class="inputbox" type="text" name="map_id" id="map_id" size="15" value="', @$row->map_id, '" />';
                    ?>
                </td>
            </tr>
            <tr>
                <td class="key">
                    <label for="title">
                        <?php echo JText::_( 'Map Title' ); ?>
                    </label>
                </td>
                <td>
                    <?php echo '<input class="inputbox" type="text" name="title" id="title" size="15" value="', @$row->title, '" />'; ?>
                </td>
            </tr>
            <tr>
                <td class="key">
                    <label for="width">
                        <?php echo JText::_( 'Width' ); ?>
                    </label>
                </td>
                <td>
                    <?php echo '<input class="inputbox" type="text" name="width" id="width" size="5" value="', @$row->width, '" />'; ?>
                </td>
            </tr>
            <tr>
                <td class="key">
                    <label for="height">
                        <?php echo JText::_( 'Height' ); ?>
                    </label>
                </td>
                <td>
                    <?php echo '<input class="inputbox" type="text" name="height" id="height" size="5" value="', @$row->height, '" />'; ?>
                </td>
            </tr>
            <tr>
                <td class="key" valign="top">
                    <label for="description">
                        <?php echo JText::_( 'Description' ); ?>
                    </label>
                </td>
                <td>
                        <?php echo '<textarea name="description" id="description" cols="80" rows="5">', @$row->description, '</textarea>'; ?>
                </td>
            </tr>
            <tr>
                <td class="key" valign="top"></td>
                <td>
                        <a href="http://www.scribblemaps.com/#id=<?php echo @$row->map_id; ?>" class="modal" rel="{handler:'iframe',size:{x:screen.availWidth-250, y:screen.availHeight-250}}">Open map editor</a>
                </td>
            </tr>
            </table>
        </fieldset>

        <div class="clr"></div>

        <input type="hidden" name="task" value="" />
        <input type="hidden" name="option" value="com_scribblemaps" />
        <input type="hidden" name="id" value="<?php echo @$row->id; ?>" />
        <input type="hidden" name="cid[]" value="<?php echo @$row->id; ?>" />
        <input type="hidden" name="textfieldcheck" value="<?php echo @$n; ?>" />
        </form>
    <?php
    }
}

$controller = new ScribbleMapsController(array('default_task' => 'showMaps'));
$task = JRequest::getVar('task');
$controller->execute(JRequest::getVar('task'));
$controller->redirect();